import React, { useState } from "react";
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Area, AreaChart } from 'recharts';
import { TrendingUp, Smile, ChevronDown } from "lucide-react";

interface MoodTrendsProps {
  data: {
    date: string;
    level: number;
  }[];
}

type TimeRange = "today" | "month" | "year";

export function MoodTrends({ data }: MoodTrendsProps) {
  const [timeRange, setTimeRange] = useState<TimeRange>("today");

  const getFilteredData = () => {
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    
    return data.filter(item => {
      const itemDate = new Date(item.date);
      switch (timeRange) {
        case "today":
          return itemDate >= today;
        case "month":
          const thirtyDaysAgo = new Date(now.setDate(now.getDate() - 30));
          return itemDate >= thirtyDaysAgo;
        case "year":
          const oneYearAgo = new Date(now.setFullYear(now.getFullYear() - 1));
          return itemDate >= oneYearAgo;
        default:
          return true;
      }
    }).map(item => ({
      ...item,
      displayDate: timeRange === "today" 
        ? new Date(item.date).toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit',
            hour12: false 
          })
        : new Date(item.date).toLocaleDateString('zh-CN')
    }));
  };

  const timeRangeOptions = {
    today: "今天",
    month: "最近30天",
    year: "最近一年"
  };

  const getEmoji = (level: number) => {
    switch (level) {
      case 1: return "😢";
      case 2: return "😔";
      case 3: return "😐";
      case 4: return "😊";
      case 5: return "😄";
      default: return "😐";
    }
  };

  const CustomTooltip = ({ active, payload, label }: any) => {
    if (active && payload && payload.length) {
      return (
        <div className="bg-card p-3 rounded-lg shadow-lg border">
          <p className="text-sm text-muted-foreground mb-1">{label}</p>
          <div className="flex items-center gap-2">
            <span className="text-xl">{getEmoji(payload[0].value)}</span>
            <span className="text-primary font-medium">
              Level {payload[0].value}
            </span>
          </div>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="bg-card rounded-xl p-6 shadow-lg">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          <TrendingUp className="w-5 h-5 text-primary" />
          <h3 className="font-bold text-lg">心情趋势</h3>
        </div>
        <div className="flex items-center gap-2">
          <Smile className="w-4 h-4 text-muted-foreground" />
          <select
            value={timeRange}
            onChange={(e) => setTimeRange(e.target.value as TimeRange)}
            className="text-sm bg-transparent border rounded-lg px-2 py-1 pr-8 appearance-none cursor-pointer hover:bg-accent transition-colors"
          >
            {Object.entries(timeRangeOptions).map(([value, label]) => (
              <option key={value} value={value}>
                {label}
              </option>
            ))}
          </select>
          <ChevronDown className="w-4 h-4 text-muted-foreground -ml-7 pointer-events-none" />
        </div>
      </div>

      <div className="h-[300px]">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart 
            data={getFilteredData()} 
            margin={{ top: 10, right: 30, left: 0, bottom: 0 }}
          >
            <defs>
              <linearGradient id="moodGradient" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.2}/>
                <stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0}/>
              </linearGradient>
            </defs>
            <CartesianGrid 
              strokeDasharray="3 3" 
              vertical={false}
              stroke="hsl(var(--muted))"
            />
            <XAxis 
              dataKey="displayDate"
              stroke="hsl(var(--muted-foreground))"
              fontSize={12}
              tickMargin={10}
              interval="preserveStartEnd"
              minTickGap={30}
            />
            <YAxis
              domain={[1, 5]}
              ticks={[1, 2, 3, 4, 5]}
              stroke="hsl(var(--muted-foreground))"
              fontSize={12}
              tickFormatter={(value) => getEmoji(value)}
            />
            <Tooltip content={<CustomTooltip />} />
            <Area
              type="monotone"
              dataKey="level"
              stroke="hsl(var(--primary))"
              strokeWidth={2}
              fill="url(#moodGradient)"
              dot={{ fill: "hsl(var(--primary))", r: 4 }}
              activeDot={{ r: 6, fill: "hsl(var(--primary))" }}
            />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
} 